from django.shortcuts import render, HttpResponse, redirect

# Create your views here.

from .models import Book


def index(request):
    books = Book.objects.all()
    return render(request, 'book_index.html', {"books": books})


def book_add(request):
    if request.method == "GET":
        return render(request, 'book_add.html')
    if request.method == "POST":
        bookname = request.POST.get('bookname')
        authorname = request.POST.get('authorname')

        Book.objects.create(name=bookname, authorname=authorname)

        return redirect('book:index')


def book_detail(request, bookid):
    book = Book.objects.get(id=bookid)
    return render(request, 'book_detail.html', {'book': book})


def book_update(request, bookid):
    book = Book.objects.get(id=bookid)
    if request.method == "GET":
        return render(request, 'book_update.html', {"book": book})
    if request.method == "POST":
        bookname = request.POST.get("bookname", "")
        authorname = request.POST.get("authorname", "")

        book.name = bookname
        book.authorname = authorname
        book.save()
        return redirect('book:index')


def book_del(request, bookid):
    """
    删除功能,不需要界面
    :param request:
    :param bookid:
    :return:
    """
    try:
        Book.objects.get(id=bookid).delete()
    except:
        return redirect('book:index')
    return redirect('book:index')
